<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      .panel-body:focus {
        outline: none;
      }

      .bs-example-popover .popover {
        position: relative;
        display: block;
        float: left;
        width: 260px;
        margin: 20px;
      }
      .msgleft{        
        float: right;
        clear: both;
      }
      .msgright{
        float: left;
        clear: both;
      }

      .popover.left {
        /* float: right; */
        margin-left: -10px;        
      }

      .popover.right {
        /* float: left; */
        margin-left: -10px;       
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
    <script>
      var websocket = null;
      function connectServer(username) {
        //判断当前浏览器是否支持WebSocket
        if ("WebSocket" in window) {
          //websocket = new WebSocket("ws://" + document.location.host + "/websocket/"+username);
          websocket = new WebSocket(
            "ws://" + document.location.host + "/server/websocket/" +username
          );
        } else {
          alert("当前浏览器 Not support websocket");
        }

        //连接发生错误的回调方法
        websocket.onerror = function() {
          setMessageInnerHTML("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function() {
          setMessageInnerHTML("WebSocket连接成功");
        };

        //接收到消息的回调方法
        websocket.onmessage = function(event) {
            console.log('原来');
          console.log("----------------------------");
          console.log(event.data);
          //setMessageInnerHTML(event.data);
        };

        //连接关闭的回调方法
        websocket.onclose = function() {

          setMessageInnerHTML("WebSocket连接关闭");
        };

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function() {
          closeWebSocket();
        };

        //关闭WebSocket连接
        function closeWebSocket() {
         console.log("关闭");
          websocket.close();
        }
        function setMessageInnerHTML(message) {
          document.getElementById("message").innerHTML = message;
        }
        return websocket;
      }
    </script>
    <script type="text/javascript">
      $(function() {
        var sendMessageTemplate  = ['       <div class="msgleft">',
'        <button class="person btn btn-primary" class="btn btn-primary" style="margin-top:30px;float:right;"></button>',
'        <div class="popover left">',
'                            <div class="arrow"></div>',
'                            <div class="popover-content">',
'                                <p class="msg"></p>',
'                            </div>',
'                        </div>',
'        </div>'].join("");;
        var acceptMessageTemplate  = ['      <div class="msgright">',
'        <button class="person btn btn-primary" style="margin-top:30px;float:left;"></button>',
'            <div class="popover right">',
'                            <div class="arrow"></div>',
'                            <div class="popover-content">',
'                                <p class="msg"></p>',
'                            </div>',
'            </div>',
'         </div>'].join("");;

        $("#connect").click(function() {
          if (!$.trim($("#username").val())) {
            alert("请输入用户名！");
            return;
          }
          window.socket = connectServer($("#username").val());
          window.socket.onmessage = function(event) {
              console.log('自定义');
            var msg = JSON.parse(event.data);
            if (msg.type && msg.type == "msg") {
                var msgDom=$(acceptMessageTemplate);
                $(".msg",msgDom).text(msg.message);
                $(".person",msgDom).text(msg.from);
                $("#chat").find("#clear").before(msgDom);
                var scrollHeight = $('#chat').prop("scrollHeight");
                $('#chat').animate({scrollTop:scrollHeight}, 300)
            }

            if(msg.type && msg.type == "onlineUser"){
                $("#online-users").html("");
                $("#online-num").html(msg.onlineUserCount);
                $.each(msg.onlineUsers,function(i,n){
                    $("#online-users").append('<li class="list-group-item">'+n+'</li>');
                })
            }
          };

          $("#send").click(function(){
            if(!window.curCustom){
                alert("请选择你要发送的人");
                return ;
            }
            msg={to:window.curCustom,message:$("#input-content").text(),msgType:"person"};
            window.socket.send(JSON.stringify(msg));
            $("#input-content").text("");
            var msgDom=$(sendMessageTemplate);
            $(".msg",msgDom).text(msg.message);
            $(".person",msgDom).text($("#username").val());
            $("#chat").find("#clear").before(msgDom);
            var scrollHeight = $('#chat').prop("scrollHeight");
            $('#chat').animate({scrollTop:scrollHeight}, 300)
          })

          $("#online-users").delegate(".list-group-item","click",function(){
            window.curCustom=$(this).html();
            $("#custom").html(window.curCustom);
          })
        });
      });
    </script>
  </head>

  <body>
    <!-- <h1>WebSocket</h1> -->

    <div class="container">
      <div class="page-header">
        <form class="form-inline">
          <div class="form-group">
            <label for="exampleInputName2">请输入自己的用户名</label>
            <input
              type="text"
              class="form-control"
              id="username"
              placeholder="用户名"
            />
          </div>
          <button id="connect" type="button" class="btn btn-default">
            上线
          </button>
          <div style="display:inline-block;width:140px;" id="message"></div>
        </form>
      </div>
      <div class="row">
        <div class="col-md-9">
          <div class="panel panel-default">
            <div class="panel-heading" style="min-height:1em"><b id="custom">&nbsp;</b> </div>
            <div id="chat" class="panel-heading bs-example-popover" style="height:350px;overflow-y: scroll">
                <div id="clear" style="clear:both"></div>
            </div>

            <div id="input-content"
              class="panel-body"
              style="height:120px;"
              contenteditable="true"
            ></div>
            <div class="panel-body" style="height:40px;padding:5px;">
              <button id="send" class="btn btn-default btn-sm" style="float:right">
                发送(S)
              </button>
            </div>
          </div>
        </div>
        <div class="col-md-3">
                <div class="panel panel-default">
                        <!-- Default panel contents -->
                        <div class="panel-heading" >在线人数(<span id="online-num">0</span>)</div>
                      
                        <!-- List group -->
                        <ul class="list-group" id="online-users">
                        </ul>
                      </div>
              
        </div>
      </div>
    </div>
  </body>
</html>
